package com.cdream.basic.thread;

import cn.hutool.core.collection.CollUtil;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author cdream
 * @date 2021/9/9
 */
public class ConditionExample {
    public static void main1(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        char[] char1 = "123456".toCharArray();
        char[] char2 = "abcdef".toCharArray();
        new Thread(() -> {
            try {
                lock.lock();
                for (char c : char1) {
                    System.out.println(c);
                    System.out.println("signal2 + start");
                    condition2.signal();
                    System.out.println("signal2 + end");
                    System.out.println("await1 + start");
                    condition1.await();
                    System.out.println("await1 + end");
                }
                condition2.signal();
            } catch (Exception ignore) {

            } finally {
                lock.unlock();
            }
        }).start();
        new Thread(() -> {
            try {
                lock.lock();
                for (char c : char2) {
                    System.out.println(c);
                    System.out.println("signal1 + start");
                    condition1.signal();
                    System.out.println("signal1 + end");
                    System.out.println("await2 + start");
                    condition2.await();
                    System.out.println("await2 + end");
                }
                condition1.signal();
            } catch (Exception ignore) {

            } finally {
                lock.unlock();
            }
        }).start();
    }

    public String findLongestWord(String s, List<String> dictionary) {
        List<String> dics = dictionary.stream().sorted(Comparator.comparing(String::length).reversed().thenComparing(String::compareTo)).collect(Collectors.toList());
        for(String dic : dics){
            if(dic.length()>s.length()){
                continue;
            }
            int i = 0;
            int j = 0;
            while(j<dic.length() && s.length()-i >= dic.length() - j){
                if(s.charAt(i)==dic.charAt(j)){
                    if(j==dic.length()-1){
                        return dic;
                    }else{
                        i++;
                        j++;
                    }
                }else{
                    i++;
                }
            }
        }
        return "";
    }

    public static void main(String[] args) {
        new ConditionExample().findLongestWord("monkey", CollUtil.newArrayList("ale","apple","monkey","abpcplea","plea","ael","eal"));
    }

}
